<template>
  <div style="margin: 10px; width: 100%">

    
    <!-- 新增地址按钮 -->
    <div style="margin-left: -180px; width: 500px;">
      <el-button plain style="background-color: #efba5d; border-color: #efba5d; color: white;" @click="addAddrText">新增地址</el-button>
    </div>
    


    <!-- 单个地址栏 -->
    <div v-for="address in addressList" :key="address.adrId" style="border: 1px solid #c1c1c1; background: white; border-radius: 10px; width: 1200px; margin: 25px auto;">
      <div style="height: 50px; background: #edf7fe; border-radius: 10px">
        <el-col :span="1" style="line-height: 15px"><p style="font-family: Sans-serif; font-size: 13pt">{{ userId }}</p></el-col>
        <el-col :span="2" style="line-height: 15px">
          <el-link type="primary" style="line-height: 50px" @click="updataAddr(address)">
            <i class="el-icon-edit"> 编辑</i>
          </el-link>
        </el-col>
        <el-col :span="17" style="line-height: 10px">&nbsp;</el-col>
        <el-col :span="4" class="el-col-close">
          <el-link class="primary delete-link" style="line-height: 50px;" @click="deleteAddress(address.adrId)">
           <i class="el-icon-delete"> 删除</i>
          </el-link>
        </el-col>
      </div>

      <div style="width: 100%">
        <div>
          <el-row style="width: 100%">
            <el-col :span="2" class="col-left"><p>收货人:&nbsp;&nbsp;</p></el-col>
            <el-col :span="22" class="col-right"><p>{{ address.acceptName }}</p></el-col>
          </el-row>
          <el-row>
            <el-col :span="2" class="col-left"><p>地址:&nbsp;&nbsp;</p></el-col>
            <el-col :span="22" class="col-right"><p>{{ address.address }}</p></el-col>
          </el-row>
          <el-row>
            <el-col :span="2" class="col-left"><p>联系电话:&nbsp;&nbsp;</p></el-col>
            <el-col :span="22" class="col-right"><p>{{ address.acceptNum }}</p></el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- 编辑地址的对话框 -->
    <el-dialog title="编辑地址" :visible.sync="editDialogVisible" width="30%">
      <el-form :model="editAddress" label-width="80px">
        <el-form-item label="收货人">
          <el-input v-model="editAddress.acceptName"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editAddress.address"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editAddress.acceptNum"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </div>
    </el-dialog>

    <!-- 新增地址的对话框 -->
    <el-dialog title="添加地址" :visible.sync="addAddrVisible" width="30%">
      <el-form :model="addAddress" label-width="80px">
        <el-form-item label="收货人">
          <el-input v-model="addAddress.acceptName"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="addAddress.address"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="addAddress.acceptNum"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addAddrVisible = false">取消</el-button>
        <el-button type="primary" @click="addAddr">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import axios from "axios";
import { jwtDecode } from "jwt-decode";

export default {
  data() {
    return {
      addressList: [],  // 地址列表
      editAddress: {}, // 当前编辑的地址信息
      editDialogVisible: false, // 控制编辑对话框

      addAddress: {}, // 新增地址信息
      addAddrVisible: false, // 控制添加地址对话框
      modifyAddrVisible: false, // 控制修改地址对话框
      userId: "",  // 用户ID
    };
  },

  methods: {
    // 获取地址列表
    getAddressList() {
      const token = localStorage.getItem("token");

      if (!token) {
        console.log("没有 token，跳转到登录页面");
        this.$router.push("/login");
        return;
      }

      // 解码 token，提取 userId
      try {
        console.log(token);  // 输出获取到的token
        console.log(jwtDecode(token));  // 解析JWT并输出

        const decoded = jwtDecode(token);  // 使用新的jwtDecode进行解析
        this.userId = decoded.userId;  // 获取 userId
        console.log("用户ID:",this.userId);

        axios
        .get("/address/getByUserId", {
          params: { userId: this.userId },
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          },
        }).then((res) => {
          this.addressList = res.data.data;
        });
      } catch (error) {
        console.error("Token 解码失败:", error);
      }
    },
    
    // 打开编辑框
    updataAddr(address) {
      this.editAddress = { ...address };
      this.editDialogVisible = true;
    },

    // 保存编辑后的地址
    saveAddress() {
      axios
        .post("/address/update", this.editAddress, {
          headers: {
            "Content-Type": "application/json",
          },
    })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("地址更新成功！");
            this.editDialogVisible = false;
            this.getAddressList(); // 更新地址列表
          } else {
            this.$message.error("更新失败，请稍后再试！");
          }
        })
        .catch(() => {
          this.$message.error("网络错误，更新失败！");
        });
    },

    addAddrText() {
      this.addAddress = { userId: this.userId, acceptName: "", address: "", acceptNum: "" };
      this.addAddrVisible = true;
    },

    // 保存编辑后的地址
    addAddr() {
      axios
        .post("/address/add", this.addAddress, {
          headers: {
            "Content-Type": "application/json",
          },
    })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("地址更新成功！");
            this.addAddrVisible = false;
            this.getAddressList(); // 更新地址列表
          } else {
            this.$message.error("更新失败，请稍后再试！");
          }
        })
        .catch(() => {
          this.$message.error("网络错误，更新失败！");
        });
    },
    
    deleteAddress(adrId) {
    // 确认删除操作
    this.$confirm('确定要删除这个地址吗?', '删除地址', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 发起删除请求
      axios
        .delete(`/address/delete`, {
          params: { adrId: adrId },  // 传递要删除的地址ID
          headers: {
            'accept': '*/*',
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success('删除地址成功');
            this.getAddressList();  // 刷新地址列表
          } else {
            this.$message.error('删除失败，请稍后再试');
          }
        })
        .catch((error) => {
          console.error('删除请求出错:', error);
          this.$message.error('网络错误，删除失败');
        });
    }).catch(() => {
      this.$message.info('已取消删除操作');
    });
  },

  },
  created() {
    this.getAddressList();
  }
};
</script>

<style scoped>
.p-green-10font {
  font-size: 10px;
  color: #50c878;
  text-align: left;
  padding-top: 5px;
}
.p-defalut-address {
  background: #8cc5ff;
  line-height: 25px;
  text-align: center;
  color: white;
  font-size: 5px;
  width: 60px;
  border-radius: 2px;
  margin-top: 12px;
}

.col-left {
  float: left;
  text-align: right;
}

.col-right {
  float: left;
  text-align: left;
}

.el-row-edit {
  text-align: right;
  margin-right: 20px;
  margin-bottom: 5px;
}

.el-col-close {
  line-height: 30px;
  text-align: right;
  padding-right: 10px;
}

.close-icon {
  background: #8cc5ff;
  width: 20px;
  height: 20px;
  margin-top: 10px;
  border-radius: 25px;
}
.delete-link {
  color: rgb(212, 12, 12);
}
.delete-link:hover {
  color: darkred;
}
</style>
